<template>
    <page-box class="container">
        <template v-slot:header>
            <ask-breadcrumb>
                <template
                    v-for="(item, index) in $getBreadCrumbsName($route.path)"
                >
                    <ask-breadcrumb-item
                        :key="index"
                        v-if="item.path"
                        :to="'/' + item.path"
                        >{{ item.meta.title }}</ask-breadcrumb-item
                    >
                    <ask-breadcrumb-item :key="index" v-else>{{
                        item.meta.title
                    }}</ask-breadcrumb-item>
                </template>
                <ask-breadcrumb-item>添加进度</ask-breadcrumb-item>
            </ask-breadcrumb>
        </template>
        <div class="body-header">
            <div class="info">
                <p>
                    <strong>{{ projectInfo.name }}</strong
                    ><span
                        :class="projectInfo.process === 100 ? 'avtive' : ''"
                        >{{
                            projectInfo.process === 100 ? "已完成" : "进行中"
                        }}</span
                    >
                </p>
                <div class="line">
                    <span>实际进度</span>
                    <el-progress
                        :percentage="projectInfo.process || 0"
                    ></el-progress>
                </div>
            </div>
            <div class="btn">
                <el-button @click="handleRestForm()">取消</el-button>
                <el-button type="primary" @click="clickSubmitForm()"
                    >提交</el-button
                >
            </div>
        </div>
        <div class="body-container">
            <h4>项目进度</h4>
            <div class="item-three">
                <span><i>*</i>所属阶段:</span>
                <el-select
                    v-model="formData.stage"
                    placeholder="请选择所属阶段"
                >
                    <el-option
                        v-for="item in processList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    >
                    </el-option>
                </el-select>
            </div>
            <div class="item-three">
                <span><i>*</i>本阶段进度:</span>
                <el-input
                    placeholder="请填写本阶段进度"
                    v-model="formData.process"
                >
                </el-input>
                <font>%</font>
            </div>
            <div class="item-one">
                <span><i>*</i>工作事项:</span>
                <el-input
                    type="textarea"
                    placeholder="请填写工作事项"
                    v-model="formData.workitems"
                    maxlength="200"
                    show-word-limit
                >
                </el-input>
            </div>
            <div class="item-one">
                <span><i>*</i>完成时间:</span>
                <el-date-picker
                    v-model="formData.endDate"
                    type="date"
                    placeholder="选择完成时间"
                    format="yyyy年MM月dd日"
                    value-format="yyyy-MM-dd"
                >
                </el-date-picker>
            </div>
            <div class="item-two">
                <span>上传图片:</span>
                <el-upload
                    ref="pictureUpload"
                    :action="$staticUrl"
                    :file-list="fileList"
                    list-type="picture-card"
                    :auto-upload="true"
                    :data="uploadData"
                    :limit="9"
                    multiple
                    :on-exceed="handleExceed"
                    :before-upload="beforeAvatarUpload"
                    :on-success="handleOnsuccess"
                >
                    <i slot="default" class="el-icon-plus"> </i>
                    <div class="el-upload__tip" slot="tip">
                        单张最大1M，最多上传9张，图片格式支持.jpg、.jpeg、.png格式
                    </div>
                    <div slot="file" slot-scope="{ file }">
                        <img
                            class="el-upload-list__item-thumbnail"
                            :src="file.url"
                            alt=""
                        />
                        <span class="el-upload-list__item-actions">
                            <span
                                class="el-upload-list__item-preview"
                                @click="handlePictureCardPreview(file)"
                            >
                                <i class="el-icon-zoom-in"></i>
                            </span>
                            <span
                                v-if="!disabled"
                                class="el-upload-list__item-delete"
                                @click="handleRemove(file)"
                            >
                                <i class="el-icon-delete"></i>
                            </span>
                        </span>
                    </div>
                </el-upload>
            </div>
            <div class="text">
                <span>领导批示:</span>
                <el-input
                    type="textarea"
                    placeholder="请填写领导批示"
                    v-model="formData.comment"
                    maxlength="300"
                    show-word-limit
                >
                </el-input>
            </div>
            <div class="text">
                <span>存在风险和问题:</span>
                <el-input
                    type="textarea"
                    placeholder="请填写存在的风险和问题"
                    v-model="formData.risk"
                    maxlength="300"
                    show-word-limit
                >
                </el-input>
            </div>
            <div class="text" style="padding-bottom:24px">
                <span>备注:</span>
                <el-input
                    type="textarea"
                    placeholder="请填写备注"
                    v-model="formData.remarks"
                    maxlength="300"
                    show-word-limit
                >
                </el-input>
            </div>
        </div>
        <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
    </page-box>
</template>

<script lang="ts">
import { Component, Mixins } from "vue-property-decorator";
import { getUUID } from "@/utils";
import AuthMixin from "@/components/public/upload/auth.mixin.ts";
@Component({
    name: "ProjectProcess"
})
export default class ProjectProcess extends Mixins(AuthMixin) {
    // 更新项目进度时需上传的数据
    formData = {
        workitems: "",
        endDate: "",
        process: "",
        stage: "",
        comment: "",
        risk: "",
        remarks: ""
    };

    // 腾讯云返回的图片信息
    sourceList: any[] = [];
    fileList: any[] = [];
    // 项目所属阶段的数组
    processList: any[] = [];
    // 图片上传腾讯云携带的参数
    uploadData: any = {
        signature: "",
        "x-cos-security-token": "",
        "Content-Type": "",
        key: "",
        dir: "",
        host: ""
    };

    dialogImageUrl = "";
    dialogVisible = false;
    disabled = false;
    path = "";

    // 当前项目的详细数据
    projectInfo = {
        name: "",
        type: "",
        investor: "",
        projectContent: "",
        totalInvestment: "",
        leadName: "",
        responsible: "",
        stageName: "",
        process: "",
        remarks: "",
        projectAuth: [],
        resImg: [],
        stage: []
    };

    created() {
        const projectID = this.$route.query.id;
        if (projectID) {
            this.getFormDetails(projectID);
        }
    }

    // 获取当前项目的详细信息以及项目进度
    async getFormDetails(id: any) {
        const [res, info] = await Promise.all([
            this.$server["project/editItem"]({
                data: {
                    id: id
                }
            }),
            this.$server["project/queryStage"]({
                data: {
                    id: id
                }
            })
        ]);
        if (res.data.code === 200) {
            this.projectInfo = res.data.data;
        }
        if (info.data.code === 200) {
            this.processList = info.data.data;
        }
    }

    // 图片上传腾讯云
    beforeAvatarUpload(file: any) {
        const isTYPE = file.type;
        const fileTypeList = ["image/jpg", "image/png", "image/jpeg"];
        const isLt6M = file.size / 1024 / 1024 < 1;
        if (!fileTypeList.includes(isTYPE)) {
            this.$message.error("上传图片只能是 JPG、PNG、JPEG 格式!");
            return false;
        }
        if (!isLt6M) {
            this.$message.error("上传图片大小不能超过 1MB!");
            return false;
        }
        return new Promise((resolve: any, reject: any) => {
            const _path = "/project-manage/img/" + new Date().format("yyyy-MM-dd") + "/" + this.path;
            this.getAuthorization({ Method: "POST", Pathname: "/" })
                .then((info: any) => {
                    this.uploadData.signature = info.Authorization;
                    this.uploadData["x-cos-security-token"] =
                        info.XCosSecurityToken;
                    this.uploadData["Content-Type"] = "";
                    this.uploadData.key =
                        _path +
                        getUUID() +
                        "." +
                        (file.file
                            ? file.file.type.split("/")[1]
                            : file.type.split("/")[1]);
                    this.uploadData.dir = _path;
                    this.uploadData.host = this.$staticUrl;
                    this.sourceList.push({
                        _id: file.uid,
                        url: this.uploadData.key + "?name=" + file.name,
                        host: this.uploadData.host
                    });
                    resolve(true);
                })
                .catch((err: any) => {
                    this.$message.error({
                        message: err.message || err.content || "接口请求失败",
                        type: "error",
                        duration: 1500
                    });
                    return reject(new Error(err));
                });
        });
    }

    // 当图片的个数超出限制时
    handleExceed(files: any, fileList: any) {
        this.$message.warning(
            `当前限制选择 9 个文件，本次选择了 ${
                files.length
            } 个文件，共选择了 ${files.length + fileList.length} 个文件`
        );
    }

    // 预览图片
    handlePictureCardPreview(file: any) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
    }

    // 删除图片时，同时更新视图和数据
    handleRemove(file: any) {
        (this.$refs.pictureUpload as any).handleRemove(file);
        const index = this.sourceList.findIndex(
            (item: any) => item._id === file.uid
        );
        const num = this.fileList.findIndex(
            (item: any) => item.uid === file.uid
        );
        this.sourceList.splice(index, 1);
        this.fileList.splice(num, 1);
    }

    handleOnsuccess(response: any, file: any, fileList: any) {
        this.fileList = fileList;
    }

    // 提交进度表单
    clickSubmitForm() {
        if (!this.formData.stage) {
            return this.$message.error("请选择所属阶段");
        }
        if (!this.formData.process) {
            return this.$message.error("请填写项目进度");
        } else {
            const reg = /^(1|([0-9]\d{0,1})|100)$/;
            if (!reg.test(this.formData.process)) {
                return this.$message.error("请输入0~100的整数");
            }
        }
        if (!this.formData.workitems) {
            return this.$message.error("请填写工作事项");
        }
        if (!this.formData.endDate) {
            return this.$message.error("请填写完成时间");
        }
        const imgList: any[] = [];
        this.sourceList.map((item: any) => {
            imgList.push(item.url);
        });
        this.$server["project/addProjectprpcess"]({
            data: {
                projectId: this.$route.query.id,
                completeTime: this.formData.endDate,
                content: this.formData.workitems,
                leaderComment: this.formData.comment,
                process: this.formData.process,
                remarks: this.formData.remarks,
                resImg: imgList,
                riskProblem: this.formData.risk,
                stageId: this.formData.stage
            }
        }).then((res: any) => {
            if (res.data.code === 200) {
                this.$message.success("进度添加成功");
                this.formData = {
                    workitems: "",
                    endDate: "",
                    process: "",
                    stage: "",
                    comment: "",
                    risk: "",
                    remarks: ""
                };
                this.fileList = [];
                this.sourceList = [];
                (this.$refs.pictureUpload as any).clearFiles();
                this.$router.push({
                    name: "ProjectList"
                });
            } else {
                this.$message.error(res.data.message);
            }
        });
    }

    // 取消进度表单
    handleRestForm() {
        this.formData = {
            workitems: "",
            endDate: "",
            process: "",
            stage: "",
            comment: "",
            risk: "",
            remarks: ""
        };
        this.fileList = [];
        (this.$refs.pictureUpload as any).clearFiles();
        this.$router.push({
            name: "ProjectList"
        });
    }
}
</script>

<style lang="scss" scoped>
* {
    margin: 0;
    box-sizing: border-box;
}
.container /deep/.page-base-body {
    background-color: transparent;
    height: unset;
}
.body-header {
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 24px;
    .info {
        display: flex;
        p {
            strong {
                font-size: 16px;
                font-family: PingFang SC;
                font-weight: 500;
                color: #2c82c9;
            }
            span {
                background: #2c82c9;
                padding: 0 10px;
                line-height: 20px;
                text-align: center;
                border-radius: 11px;
                color: #ffff;
                margin-left: 10px;
                font-size: 12px;
                font-weight: 400;
                font-family: "PingFang SC Medium";
                &.avtive {
                    background-color: #32a78f !important;
                }
            }
        }
    }
    .btn {
        display: flex;
        justify-content: space-between;
    }
    /deep/.line {
        display: flex;
        align-items: center;
        margin-left: 6px;
        span {
            font-size: 14px;
            color: #37383a;
            margin-right: 6px;
        }
        .el-progress.el-progress--line {
            width: 172px;
        }
        .el-progress-bar__outer {
            width: 120px;
        }
    }
}
.body-container {
    background: #ffffff;
    padding-top: 12px;
    margin-top: 10px;
    & > div {
        margin-top: 18px;
    }
    h4 {
        font-size: 16px;
        color: #37383a;
        padding-left: 24px;
    }
    .item-one {
        display: flex;
        /deep/ .el-textarea {
            width: 480px;
            textarea {
                height: 80px;
                resize: none;
            }
        }
        .el-input {
            width: 480px;
        }
        span {
            display: inline-block;
            width: 126px;
            font-size: 14px;
            text-align: right;
            padding-right: 12px;
            color: #6b6c70;
            i {
                font-style: normal;
                color: #de2728;
            }
        }
    }
    .item-two {
        display: flex;
        & > span {
            display: inline-block;
            width: 126px;
            font-size: 14px;
            text-align: right;
            padding-right: 12px;
            color: #6b6c70;
        }
    }
    .item-three {
        display: flex;
        align-items: center;
        span {
            display: block;
            width: 126px;
            font-size: 14px;
            text-align: right;
            color: #6b6c70;
            padding-right: 12px;
            i {
                font-style: normal;
                color: #de2728;
            }
        }
        .el-input,
        .el-select {
            width: 480px;
        }
        font {
            margin-left: 6px;
            font-size: 14px;
            color: #6b6c70;
        }
    }
    .text {
        display: flex;
        /deep/ .el-textarea {
            height: 80px;
            width: 480px;
            textarea {
                height: 80px;
                resize: none;
            }
        }
        span {
            display: inline-block;
            width: 126px;
            font-size: 14px;
            text-align: right;
            padding-right: 12px;
            color: #6b6c70;
        }
    }
    /deep/.el-upload {
        position: relative;
        .el-upload--picture-card i {
            font-size: 24px;
        }
        .el-icon-plus {
            width: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
    }
    /deep/.el-upload__tip {
        font-size: 12px;
        color: #6b6c70 !important;
        margin-top: 7px;
    }
}
</style>
